﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Clipping.Infrastructure.Models;
using System.Web;
using System.Text.RegularExpressions;

namespace Clipping.Utils.SearchEngines
{
    public class QihooNews : ISearchEngine
    {
        private Encoding _urlEncoding = Encoding.GetEncoding("gb2312");
        private Encoding _contentEncoding = Encoding.UTF8;
        public string Name
        {
            get { return "360新闻搜索"; }
        }

        public Encoding ContentEncoding
        {
            get { return _contentEncoding; }
        }

        public void Parse(Uri url, string html, out List<Infrastructure.Models.News> news, out string nextPageUrl)
        {
            parse(html, out news, out nextPageUrl);
            if (!string.IsNullOrEmpty(nextPageUrl))
                nextPageUrl = constructAbsoluteUrl(url, nextPageUrl).OriginalString;
            if (news != null)
            {
                foreach (var n in news)
                {
                    if (!string.IsNullOrEmpty(n.SameNewsUrl))
                        n.SameNewsUrl = constructAbsoluteUrl(url, n.SameNewsUrl).OriginalString;
                }
            }
        }

        public Uri ConstructUrl(Infrastructure.Models.SearchObject searchObj)
        {
            string tn = "news";
            if (searchObj.SearchType == SearchType.SearchInTitle)
                tn = "newstitle";
            string url = string.Format("http://news.so.com/ns?q={0}&tn={1}&rank=pdate", HttpUtility.UrlEncode(searchObj.Keyword, this._urlEncoding), tn);
            return new Uri(url);

        }



        private Uri constructAbsoluteUrl(Uri baseUri, string url)
        {
            return UriHelper.ConstructAbsoluteUrl(baseUri, url);
        }

        public void parse(string html, out List<Infrastructure.Models.News> news, out string nextPageUrl)
        {
            news = new List<News>();
            nextPageUrl = null;
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);

            var liNav = doc.CreateNavigator();

            var divContentSearch = liNav.Select("//div[@id='container']//li");
            while (divContentSearch.MoveNext())
            {
                News n = new News();

                var li = divContentSearch.Current;

                //取标题和链接
                var linkNode = li.SelectSingleNode("descendant::h3/a");
                if (linkNode != null)
                {
                    n.Title = linkNode.Value;
                    n.Url = linkNode.GetAttribute("href", "");
                    if (!string.IsNullOrEmpty(n.Url))
                        n.Url = System.Web.HttpUtility.HtmlDecode(n.Url);
                }

                //取媒体及时间
                var mediaAndDateNode = li.SelectSingleNode("descendant::h3/span");
                var mediaAndDate = System.Web.HttpUtility.HtmlDecode(mediaAndDateNode.Value);
                var time = mediaAndDateNode.GetAttribute("title", null);
                n.Media = Regex.Split(mediaAndDate, "\\s+", RegexOptions.None).FirstOrDefault();
                n.PubDate = time;

                //取摘要

                var summary = li.Value.Replace(li.SelectSingleNode("descendant::h3").Value, "");
                n.Summary = summary;


                //相同新闻
                var sameNews = li.Select("descendant::a");
                while (sameNews.MoveNext())
                {
                    Match m = Regex.Match(sameNews.Current.Value, @"(\d+)\s*条相同新闻");
                    if (m.Success)
                    {
                        n.SameNewsUrl = sameNews.Current.GetAttribute("href", "");
                        n.SameNewsCount = int.Parse(m.Groups[1].Value);
                        break;
                    }
                }

                news.Add(n);
            }


            var nextPage = liNav.Select("//div[@id='page']/a");
            while (nextPage.MoveNext())
            {
                if (nextPage.Current.Value != null && nextPage.Current.Value.Contains("下一页"))
                {
                    nextPageUrl = nextPage.Current.GetAttribute("href", "");
                    if (!string.IsNullOrEmpty(nextPageUrl))
                        nextPageUrl = System.Web.HttpUtility.HtmlDecode(nextPageUrl);
                }
            }
        }

    }
}
